import * as PIXI from 'pixi.js';
import { GameConfig } from '../config';
import { Vehicle, VehicleType, Direction } from '../entities/vehicle';

export class VehicleManager {
    public container: PIXI.Container;
    private config: GameConfig;
    private vehicles: Vehicle[] = [];
    private lastSpawnTime: { up: number; down: number } = { up: 0, down: 0 };
    private spawnInterval: number;
    private isActive: boolean = false;
    private laneOccupied: boolean[];  // 6车道
    private currentLevel: number = 1;

    constructor(config: GameConfig) {
        this.config = config;
        this.container = new PIXI.Container();
        this.spawnInterval = config.spawn.initialInterval;
        
        // 初始化车道占用状态（6个车道）
        this.laneOccupied = new Array(config.laneCount).fill(false);
        
        // 设置容器位置
        this.container.x = 0;
        this.container.y = 0;
    }

    public start(level: number): void {
        this.isActive = true;
        this.currentLevel = level;
        this.lastSpawnTime = 0;
        this.laneOccupied.fill(false);
    }

    public update(delta: number, currentSpeed: number): void {
        if (!this.isActive) return;
        
        // 更新现有车辆
        this.updateVehicles(currentSpeed, delta);
        
        // 生成新车辆
        this.lastSpawnTime += delta * (1000 / 60);  // 转换为毫秒
        if (this.lastSpawnTime >= this.spawnInterval) {
            this.spawnVehicle();
            this.lastSpawnTime = 0;
        }
        
        // 清理离开屏幕的车辆
        this.cleanupVehicles();
    }

    private updateVehicles(speed: number, delta: number): void {
        for (const vehicle of this.vehicles) {
            vehicle.update(speed, delta);
        }
    }

    private spawnVehicle(): void {
        // 计算实际可用的车道数（6个车道）
        const roadWidth = this.config.screenWidth - 2 * this.config.roadOffset;
        const laneWidth = roadWidth / 6;  // 固定6个车道
        
        // 获取可用车道（只考虑6个车道）
        const availableLanes = this.laneOccupied
            .slice(0, 6)  // 只使用前6个车道
            .map((occupied, index) => ({ index, occupied }))
            .filter(lane => !lane.occupied)
            .map(lane => lane.index);

        if (availableLanes.length === 0) return;  // 如果没有可用车道，不生成新车辆

        // 随机选择一个可用车道
        const laneIndex = availableLanes[Math.floor(Math.random() * availableLanes.length)];
        
        // 随机选择车型
        const vehicleType = this.selectRandomVehicleType();
        
        // 决定是否生成超速车辆（15%的概率）
        const isSpeedster = Math.random() < 0.15;
        const speedMultiplier = isSpeedster ? 2.0 : 1;
        
        // 计算车辆的实际X坐标（考虑道路偏移）
        const x = this.config.roadOffset + laneIndex * laneWidth;
        
        // 创建车辆
        const vehicle = new Vehicle(
            vehicleType,
            this.config.vehicles[vehicleType],
            x,  // 直接传入x坐标
            laneWidth,
            'down',  // 所有车辆都向下行驶
            speedMultiplier
        );
        
        // 标记车道为占用状态
        this.laneOccupied[laneIndex] = true;
        
        // 添加到容器
        this.vehicles.push(vehicle);
        this.container.addChild(vehicle);
    }

    private selectRandomVehicleType(): VehicleType {
        const random = Math.random();
        let sum = 0;
        
        for (const [type, config] of Object.entries(this.config.vehicles)) {
            sum += config.probability;
            if (random <= sum) {
                return type as VehicleType;
            }
        }
        
        return 'car';  // 默认返回轿车
    }

    private cleanupVehicles(): void {
        const screenHeight = this.config.screenHeight;
        
        // 移除离开屏幕的车辆
        this.vehicles = this.vehicles.filter(vehicle => {
            const y = vehicle.y;
            
            // 检查是否离开屏幕
            if (y > screenHeight + 100) {  // 向下移动的车辆
                // 释放车道占用
                this.laneOccupied[vehicle.getLane()] = false;
                this.container.removeChild(vehicle);
                return false;
            }
            return true;
        });
    }

    public checkCollisionWithShadow(shadowRect: PIXI.Rectangle): { collided: boolean; point?: PIXI.Point } {
        for (const vehicle of this.vehicles) {
            if (!vehicle.isActive) continue;
            
            const vehicleBounds = vehicle.getBounds();
            const collisionPoint = this.checkCollision(shadowRect, vehicleBounds);
            
            if (collisionPoint) {
                return { collided: true, point: collisionPoint };
            }
        }
        return { collided: false };
    }

    private checkCollision(shadowRect: PIXI.Rectangle, vehicleRect: PIXI.Rectangle): PIXI.Point | null {
        // 检查两个矩形是否相交
        if (shadowRect.x < vehicleRect.x + vehicleRect.width &&
            shadowRect.x + shadowRect.width > vehicleRect.x &&
            shadowRect.y < vehicleRect.y + vehicleRect.height &&
            shadowRect.y + shadowRect.height > vehicleRect.y) {
            
            // 计算碰撞点（使用相交区域的中心点）
            const intersectX = Math.max(shadowRect.x, vehicleRect.x);
            const intersectY = Math.max(shadowRect.y, vehicleRect.y);
            const intersectWidth = Math.min(shadowRect.x + shadowRect.width, vehicleRect.x + vehicleRect.width) - intersectX;
            const intersectHeight = Math.min(shadowRect.y + shadowRect.height, vehicleRect.y + vehicleRect.height) - intersectY;
            
            return new PIXI.Point(
                intersectX + intersectWidth / 2,
                intersectY + intersectHeight / 2
            );
        }
        
        return null;
    }

    public getCurrentSpeed(baseSpeed: number): number {
        // 根据关卡计算当前速度（实际移动速度是基础速度的2倍）
        return baseSpeed * 2 * Math.pow(1 + this.config.speed.increaseRate, this.currentLevel - 1);
    }

    public getSpeedInKmh(): number {
        // 显示速度保持在60km/h开始
        const baseKmh = 60;  // 第一关显示速度（60km/h）
        return baseKmh * Math.pow(1 + this.config.speed.increaseRate, this.currentLevel - 1);
    }

    public reset(): void {
        // 清除所有车辆
        for (const vehicle of this.vehicles) {
            this.container.removeChild(vehicle);
        }
        this.vehicles = [];
        
        // 重置状态
        this.isActive = false;
        this.lastSpawnTime = 0;
        this.spawnInterval = this.config.spawn.initialInterval;
        this.laneOccupied.fill(false);
    }

    public increaseSpeed(): void {
        // 增加生成频率
        this.spawnInterval = Math.max(
            this.config.spawn.minInterval,
            this.spawnInterval * 0.9  // 每关生成间隔减少10%
        );
    }
}